/*
 *  $Id$
 *  Copyright [2010] [Panxiaobo] 
 *  Licensed under the Apache License, Version 2.0 (the "License"); 
 *  you may not use this file except in compliance with the License. 
 *  You may obtain a copy of the License at
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 *  Unless required by applicable law or agreed to in writing, software 
 *  distributed under the License is distributed on an "AS IS" BASIS, 
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 *  See the License for the specific language governing permissions and 
 *  limitations under the License. 
 */
package pxb.openid.rp;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pxb.openid.Association;
import pxb.openid.Constants;
import pxb.openid.Forward;

/**
 * 生成验证请求
 * 
 * @author Panxiaobo
 * 
 */
public class Auth implements Constants {
    private static final Logger log = LoggerFactory.getLogger(Auth.class);

    public Forward generate(Association association, Map<String, String> otherParams, String server, String claimedId,
            String returnTo) {
        return generate(association, otherParams, server, claimedId, returnTo, null);
    }

    /**
     * 9. Requesting Authentication
     * 
     * @param context
     * @param returnTo
     * @param realm
     * @return
     */
    public Forward generate(Association association, Map<String, String> otherParams, String server, String claimedId,
            String returnTo, String realm) {
        Map<String, String> urlParams = otherParams == null ? new HashMap<String, String>()
                : new HashMap<String, String>(otherParams);
        urlParams.put(OPENID_NS, OPENID_20_NAMESPACE);
        urlParams.put(OPENID_MODE, CHECKID_SETUP);
        urlParams.put(OPENID_IDENTITY, ID_SELECT);
        // urlParams.put(OPENID_CLAIMED_ID, claimedId);
        urlParams.put(OPENID_CLAIMED_ID, ID_SELECT);
        urlParams.put(OPENID_RETURN_TO, returnTo);
        urlParams.put(OPENID_ASSOCIATION_HANDLE, association.getId());
        if (realm != null)
            urlParams.put(OPENID_REALM, realm);
        else
            urlParams.put(OPENID_REALM, returnTo);

        if (log.isDebugEnabled()) {
            log.debug("RP->OP auth request params:");
            log.debug("server: {}", server);
            log.debug("==================== Start");
            Map<String, String> map = new TreeMap<String, String>(urlParams);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                log.debug("{} = {}", entry.getKey(), entry.getValue());
            }
            log.debug("==================== End");
        }

        return new Forward(server, urlParams);
    }
}
